//
//  HappiGoServer.m
//  HappiGO
//
//  Created by Zhuo LaiQiang on 11-9-26.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "TaoBaoServer.h"
#import "MBProgressHUD.h"
#import "JSON.h"

@implementation TaoBaoServer

@synthesize dic = _dic;
@synthesize urlStr = _urlStr;
@synthesize select = _select;
@synthesize isFaileSelect = _isFaileSelect;
@synthesize parameterDic = _parameterDic;

//字符串编码方式
NSString *getURLCreateString(NSString *url)
{
    NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                  (CFStringRef)url,
                                                                                  NULL,
                                                                                  NULL,
                                                                                  kCFStringEncodingUTF8);
    return [encodedString autorelease];
}

- (void)cancelRequest
{
        [_request clearDelegatesAndCancel];
        //[_request release];
        _request = nil;
    
}

- (void)dealloc
{
    if (_dic)
    {
        [_dic release];
    }
    
    [self cancelRequest];
    [_urlStr release];
    [_parameterDic release];
    self.select = nil;
    _isFaileSelect = nil;
    
    [super dealloc];
}

- (id)initWithUrl:(NSString *)urlStr_ object:(id)object_ select:(SEL)sel showWaitView:(BOOL)ctr_
{
    self = [super init];
    
    if (self)
    {
        _object = object_;
        _select = sel;
        _showWaitView = ctr_;
        
        //进行URL编码
        NSArray *comp1 = [urlStr_ componentsSeparatedByString:@"?"];
        NSString *baseUrlStr = [comp1 objectAtIndex: 0];
        NSString *query = [comp1 lastObject];
        
        NSArray *queryElements = [query componentsSeparatedByString:@"&"];
        NSMutableString *url = [NSMutableString stringWithFormat: @"%@?", baseUrlStr];
        for (int i = 0; i < [queryElements count]; i++)
        {
            NSString *element = [queryElements objectAtIndex: i];
            
            //ITTDINFO(@"%@", element);
            
            NSArray *keyVal = [element componentsSeparatedByString:@"="];
            ITTDINFO(@"%@", keyVal);
            NSString *variableKey = [keyVal objectAtIndex:0];
            ITTDINFO(@"%@", variableKey);
            
            NSString *value = getURLCreateString([keyVal objectAtIndex: 1]);
            [url appendFormat: @"%@=%@", variableKey, value];
            
            if (i != [queryElements count] - 1) 
            {
                [url appendString: @"&"];
            }
        }
        
        self.urlStr = url;
        
        ITTDINFO(@"请求的网址: %@", url);
    }
    
    return self;
}

//支持get和post方法并用
- (id)initWithUrl:(NSString *)urlStr_ object:(id)object_ select:(SEL)sel parameter:(NSDictionary *)parameterDic_ showWaitView:(BOOL)ctr_
{
    self = [super init];
    
    if (self)
    {
        _object = object_;
        _select = sel;
        _showWaitView = ctr_;
        //self.urlStr = urlStr_;
        self.parameterDic = parameterDic_;
        
        //进行URL编码
        NSArray *comp1 = [urlStr_ componentsSeparatedByString:@"?"];
        NSString *baseUrlStr = [comp1 objectAtIndex: 0];
        NSString *query = [comp1 lastObject];
        
        NSArray *queryElements = [query componentsSeparatedByString:@"&"];
        NSMutableString *url = [NSMutableString stringWithFormat: @"%@?", baseUrlStr];
        for (int i = 0; i < [queryElements count]; i++)
        {
            NSString *element = [queryElements objectAtIndex: i];
            
            //ITTDINFO(@"%@", element);
            
            NSArray *keyVal = [element componentsSeparatedByString:@"="];
            ITTDINFO(@"%@", keyVal);
            NSString *variableKey = [keyVal objectAtIndex:0];
            ITTDINFO(@"%@", variableKey);
            
            NSString *value = getURLCreateString([keyVal objectAtIndex: 1]);
            [url appendFormat: @"%@=%@", variableKey, value];
            
            if (i != [queryElements count] - 1) 
            {
                [url appendString: @"&"];
            }
        }
        
        self.urlStr = url;

        
        ITTDINFO(@"请求的网址: %@", self.urlStr);
    }
    
    return self;
}

- (id)initWithUrl:(NSString *)urlStr_ 
           object:(id)object_ 
requestIsEndSelect:(SEL)endSelect 
requestIsFailSelect:(SEL)failSelect 
     showWaitView:(BOOL)ctr_
urlEncode:(BOOL)encode_
{
    self = [super init];
    
    if (self)
    {
        _object = object_;
        _select = endSelect;
        _isFaileSelect = failSelect;
        _showWaitView = ctr_;
        
        if (encode_)
        {
        //进行URL编码
        NSArray *comp1 = [urlStr_ componentsSeparatedByString:@"?"];
        NSString *baseUrlStr = [comp1 objectAtIndex: 0];
        NSString *query = [comp1 lastObject];
        
        NSArray *queryElements = [query componentsSeparatedByString:@"&"];
        NSMutableString *url = [NSMutableString stringWithFormat: @"%@?", baseUrlStr];
        for (int i = 0; i < [queryElements count]; i++)
        {
            NSString *element = [queryElements objectAtIndex: i];
            
            //ITTDINFO(@"%@", element);
            
            NSArray *keyVal = [element componentsSeparatedByString:@"="];
            ITTDINFO(@"%@", keyVal);
            NSString *variableKey = [keyVal objectAtIndex:0];
            ITTDINFO(@"%@", variableKey);
            
            NSString *value = getURLCreateString([keyVal objectAtIndex: 1]);
            [url appendFormat: @"%@=%@", variableKey, value];
            
            if (i != [queryElements count] - 1) 
            {
                [url appendString: @"&"];
            }
        }
            self.urlStr = url;
             ITTDINFO(@"请求的网址: %@", url);
        }else
        {
        
        self.urlStr = urlStr_;
             ITTDINFO(@"请求的网址: %@", urlStr_);
        }
    }
    
    return self;
}

- (void)startAsynchronousRequest
{
    [self cancelRequest];
    
    ITTDINFO(@"%@", _urlStr);
    _request = [ASIFormDataRequest requestWithURL: [NSURL URLWithString: _urlStr]];
    _request.delegate = self;
    _request.timeOutSeconds = 30.0;
    _request.numberOfTimesToRetryOnTimeout = 2;
    if (_parameterDic)
    {
        //ITTDINFO(@"%@", _parameterDic);
        for (NSString *key in _parameterDic)
        {
            NSString *value = [_parameterDic objectForKey: key];
            [_request setPostValue: value forKey: key];
            ITTDINFO(@"key = %@ value = %@",key, value);
        }
    }
    
    [_request startAsynchronous];
}

#pragma mark - ASIHTTPRequestDelegate
//开始网络连接
- (void)requestStarted:(ASIHTTPRequest *)request
{
    ITTDPRINT(@"开始请求网络");
    
    if (_showWaitView)
    {
        if (_object && [_object isKindOfClass: [UIViewController class]])
        {
            [MBProgressHUD hideHUDForView:((UIViewController *)_object).view animated: YES];//有可能请求多次
            [MBProgressHUD showHUDAddedTo: ((UIViewController *)_object).view animated: YES];
        }else if(_object && [_object isKindOfClass: [UIView class]])
        {
            [MBProgressHUD hideHUDForView: (UIView *)_object animated: YES];//有可能请求多次
            [MBProgressHUD showHUDAddedTo: (UIView *)_object animated: YES];
        }
    }
}

- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
    ITTDPRINT(@"网络请求获取到headers: %@", responseHeaders);
}

//完成网络连接
- (void)requestFinished:(ASIHTTPRequest *)request
{
    ITTDINFO(@"%@", [request url]);
    //后期修改为多线程解析json
    
    // ITTDINFO(@"data = %@", [_request responseData]);
    // ITTDINFO(@"responseString: %@", [_request responseString]);
    NSString *tempStr = [[_request responseString] stringByReplacingOccurrencesOfString: @"null" withString: @"\"\""];
    // ITTDINFO(@"\n\n\n\n\n\n%@", tempStr);
    
    self.dic = [tempStr JSONValue];
    
    ITTDPRINT(@"网络请求完成\n %@", self.dic);
    
    if (_dic) 
    {
        if (_object && [_object respondsToSelector: _select])
        {
            [_object performSelector: _select withObject: self];
        }
    }
    else
    {    
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle: nil message: @"服务器忙，请稍候再试" delegate: nil cancelButtonTitle: @"确定" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
    _request = nil;
    
    if (_showWaitView)
    {
        if (_object &&([_object isKindOfClass: [UIViewController class]]))
        {
            [MBProgressHUD hideHUDForView:((UIViewController *)_object).view animated: YES];
        }
        else if (_object &&([_object isKindOfClass: [UIView class]]))
        {
            [MBProgressHUD hideHUDForView:(UIView *)_object animated: YES];
        }
    }
}

//网络链接失败
- (void)requestFailed:(ASIHTTPRequest *)request
{
    
    ITTDINFO(@"%@", [request url]);
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:  @"提示" message: @"没有检测到网络" delegate: nil cancelButtonTitle: @"确定" otherButtonTitles: nil];
    [alert show];
    [alert release];
    
    if (_showWaitView)
    {
        if (_object)
        {
            [MBProgressHUD hideHUDForView:((UIViewController *)_object).view animated: YES];
        }
    }
    
    if (_object && [_object respondsToSelector: _isFaileSelect])
    {
        [_object performSelector: _isFaileSelect withObject: self];
    }
    
    _request = nil;
}

@end
